package com.suitsoft.bdms.service.account;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.suitsoft.bdms.commos.LoginUser;
import com.suitsoft.bdms.dao.account.RoleDao;
import com.suitsoft.bdms.dao.account.UserDao;
import com.suitsoft.bdms.entity.account.Authority;
import com.suitsoft.bdms.entity.account.Role;
import com.suitsoft.bdms.entity.account.User;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	private AccountManager accountManager;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	
	private final Long GENERAL_USER_ROLE_ID = 20030L;

	/**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		//这里判断。如果。不是从登陆页面传过来 的。
		String password = null;
		String[] ss = username.split("~!@");
		if(ss.length == 2){
			String name = ss[0];
			password = ss[1] == null ? "" : ss[1];
			username = name;
		}
		
		System.out.println(password);
		
		User user = accountManager.findUserByLoginName(username);
		LoginUser userdetails = null;
		
		//-- bdms示例中无以下属性, 暂时全部设为true. --//
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		
		Set<GrantedAuthority> grantedAuths = null;
		
		try {
			if(user == null){
				Map<String,Object> syncUser = accountManager.findSyncUser(username);
				if(syncUser == null || syncUser.isEmpty()){
					return null;
				}
				
				List<Map<String,Object>> passwordList = accountManager.findSyncPassword(Long.valueOf(syncUser.get("ID").toString()), null);
				if(passwordList == null || passwordList.isEmpty()){
					return null;
				}
				
				for(Map<String,Object> m : passwordList){
					if(password.equals(m.get("PASSWORD"))){
						grantedAuths = obtianGrantedAuthorithiesForGeneral();
						userdetails = new LoginUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
						
						userdetails.setLoginName(username);
						userdetails.setName(username);
						userdetails.setPassword(password);
						userdetails.getRoleList().add(roleDao.get(GENERAL_USER_ROLE_ID));
						userdetails.setId(Long.valueOf(m.get("ID").toString()));
						return userdetails;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		
		
		
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		grantedAuths = obtainGrantedAuthorities(user);

		
		
//		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getLoginName(), user
//				.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
		

		userdetails = new LoginUser(user.getLoginName(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
		
		userdetails.setLoginName(user.getLoginName());
		userdetails.setName(user.getName());
		userdetails.setPassword(user.getPassword());
		userdetails.setRoleList(user.getRoleList());
		userdetails.setSystemList(user.getSysteList());
		userdetails.setId(user.getId());
		userdetails.setTree(userDao.getTree(user.getId()));
		return userdetails;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Authority authority : role.getAuthorityList()) {
				authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
			}
		}
//		for(SubSystem ss : user.getSysteList()){
//			for(Role r : ss.getRoleList()){
//				for (Authority authority : r.getAuthorityList()) {
//					authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
//				}
//			}
//		}
		return authSet;
	}
	
	/**
	 * 获取普通用户有权限集合
	 * <pre>就是获取普通用户角色(是指定的一个)</pre>
	 * @return
	 */
	private Set<GrantedAuthority> obtianGrantedAuthorithiesForGeneral(){
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		//这里是固定的
		//从子系统获取的用户信息视为普通用户
		Role role = roleDao.get(GENERAL_USER_ROLE_ID);
		for(Authority a : role.getAuthorityList()){
			authSet.add(new GrantedAuthorityImpl(a.getPrefixedName()));
		}
		return authSet;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
}
